<template>
    <button class="codeBtn" @click="$emit('getCode')" :disabled="isDisabled">
        <template v-if="isDisabled">{{count}}秒</template>
        <template v-else>{{text}}</template>
    </button>
</template>

<script>
import { reactive,toRefs,onBeforeUnmount } from 'vue'
export default {
    props:{
      time:{ // 倒计时:秒
        type:Number,
        default:60
      }
    },
    setup(props,context){
        const state = reactive({
            text:"获取验证码",
            count:props.time,
            isDisabled:false,
            st:''
        })

        const countDown = ()=> {  // 倒计时
            if (state.count > 0) {
                state.isDisabled = true
                clearTimeout(state.st)
                state.st = setTimeout(() => {
                    state.count--
                    countDown()
                }, 1000)
            } else {
                state.count = props.time
                //context.emit('update:disabled', false)
                state.isDisabled = false
                state.text = '获取验证码'
            }
        }

        onBeforeUnmount(()=>{  // 销毁组件
            clearTimeout(state.st)
            console.log('关闭倒计时')
        })
        
        return{
            ...toRefs(state),
            countDown
        }
    }
}
</script>

<style lang="scss" scoped>
    .codeBtn{
        display: block;
        position: absolute;
        z-index: 10;
        right: 0;
        top: 32px;
        text-align: center;
        padding: 0;
        border: 0;
        min-width: 160px;
        height: 50px;
        line-height: 50px;
        background: #0E6161;
        border-radius: 32px 32px 32px 32px;
        opacity: 1;
        color: #fff;
        font-size: 24px;
        padding: 0 15px;
        &:disabled{
            color: #c4c1c1;
            background: #7c7f7f;
        }
    }
</style>